﻿<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>我秀地图-驾车线路规划</title>
    <link href="" rel="shortcut icon" type="image/x-icon"/>
    <meta charset="utf-8"/>
    <link href="../css/imap-gl.css" rel="stylesheet"/>
    <script src="../js/imap-gl.js"></script>
    <style>
        html, body {
            padding: 0;
            margin: 0;
            height: 100%;
            overflow: hidden;
        }

        #map {
            height: 100%;
            z-index: 0;
        }

    </style>
</head>
<body>
<div id='map'></div>
<script>
  
    var map = new imapgl.Map({
        container: 'map',
        center: [116.27771321722543, 39.952128183377255],
        zoom: 3,
        minZoom: 3,
        hash: true,
        maxZoom: 20,
        localIdeographFontFamily: "微软雅黑, 'Microsoft Sans Serif', sans-serif,宋体",
        antialias: false,
        style: "../styles/v1/light-v10-gcj02-lc.json"
    });

    //坐标msp服务实例
    var msp = new imapgl.MspControl()

    var options = {
             origin: "116.26974609172504,39.93711186994827",
        destination: "116.29362092258657,39.97994930392781",
        coord_type: "",
        waypoints: "",
        tactics: 11,
        avoidpolygons: "",
        avoidroad: "",
        out_coord_type: ""
    }
    /* 驾车线路规划
     * options                          入参对象
     * options.origin string            起点经纬度，或起点名称+经纬度，此时名称只用于展示。格式如：中关村皇冠假日酒店写字楼| 116.32259,39.97554;必填参数
     * options.destination string       终点经纬度，或终点名称+经纬度，此时名称只用于展示。格式如：中关村皇冠假日酒店写字楼| 116.32259,39.97554;必填参数
     * options.coord_type string        坐标类型，默认为gcj02。允许的值为： gcj02： 国测局坐标 wgs84： gps设备获取的坐标 baidu : 百度坐标;可选参数
     * options.tactics int              路径规划策略，对应的状态码如下：0：费用优先（不走收费路段的最快道路）；2：国道优先；4：省道优先；5：不走高速； 6：多策略1（同时返回速度优先、费用优先、距离优先的路径各一条）；10：不走快速路（不走快速路，不包含高速路）；11：速度优先（快速路优先）；12：距离优先（路径最短）。默认值为11。可选参数
     * options.avoidpolygons string     区域避让，支持32个避让区域，每个区域最多可有16个顶点 。 经、纬度之间用","分割，小数点后不超过6位，坐标点之间用";"分隔，区域之间用"|"分隔。如果是四边形则有四个坐标点，如果是五边形则有五个坐标点。格式如：经度,纬度;经度,纬度;经度,纬度|经度,纬度;经度,纬度;经度,纬度......说明：当避让道路与避让区域同时输入时，避让道路有效.可选参数
     * options.avoidroad string         避让道路名称，支持输入一条道路名称。选填参数
     * options.out_coord_type string    坐标类型，默认为gcj02。允许的值为： gcj02： 国测局坐标 wgs84： gps设备获取的坐标 baidu : 百度坐标;可选参数
     *
     * return
     * data                             返回值对象
     * data.status	                    状态，0为成功，其他为失败。
     * data.message	                    状态说明。
     * data.total	                    检索到的类型记录总数。
     * data.results	                    检索结果。
     * */
    msp.Driving(options, function (data) {
        console.log(data)
        var linearrs = []
        var lineArr = new Array();
        if (data.status == "0") {
            var routes = data.result.routes;
            for (var i = 0; i < routes.length; i++) {
                var steps = routes[i].steps;
                for (var k = 0; k < steps.length; k++) {
                    var path = steps[k].path;
                    lineArr.push(path)
                }
            }
        }
        if (lineArr.length > 0) {
            var StringLine = lineArr.join(";");
            var str = StringLine.split(";");
            for (var i = 0; i < str.length; i++) {
                var str_c = new Array();

                linearrs[i] = [Number(str[i].split(",")[0]), Number(str[i].split(",")[1])];
            }


            //起点
            addMarker("marker_blue",str[0]);
            //终点
            addMarker("marker_red", str[str.length - 1]);
            //画线
            drawLine(linearrs);

            center(str[0], str[str.length - 1])

        }
    })

    function center(beginlnglat, endlnglat) {
        var beginlnglat = beginlnglat.split(",");
        var endlnglat = endlnglat.split(",");

        var xx = [Number(beginlnglat[0]), Number(endlnglat[0])]
        var yy = [Number(beginlnglat[1]), Number(endlnglat[1])]

        xx.sort()
        yy.sort()
        var bbox = [
            [Number(xx[0]), Number(yy[0])],
            [Number(xx[1]), Number(yy[1])]
        ];
        map.fitBounds(bbox, {
            padding: {
                top: 100,
                bottom: 100,
                left: 100,
                right: 100
            }
        });
    }

    function drawLine(lines) {
        map.addSource('route', {
            'type': 'geojson',
            'data': {
                'type': 'Feature',
                'properties': {},
                'geometry': {
                    'type': 'LineString',
                    'coordinates': lines
                }
            }
        });
        map.addLayer({
            "id": "navLines-style-1",
            "type": "line",
            "source": "route",
            "layout": {
                "visibility": "visible",
                "line-join": "round",
                "line-cap": "butt"
            },
            "paint": {
                "line-translate-anchor": "viewport",
                "line-width": {
                    "stops": [
                        [
                            7,
                            5
                        ],
                        [
                            18,
                            16
                        ]
                    ],
                    "base": 1.2
                },
                "line-color": "#459C50"
            },
            "interactive": true
        });

        map.addLayer({
            "id": "navLines-style-2",
            "type": "line",
            "source": "route",
            "layout": {
                "visibility": "visible",
                "line-join": "round",
                "line-cap": "butt"
            },
            "paint": {
                "line-translate-anchor": "viewport",
                "line-width": {
                    "stops": [
                        [
                            7,
                            5
                        ],
                        [
                            18,
                            16
                        ]
                    ],
                    "base": 1.2
                },
                "line-dasharray": [
                    2,
                    5
                ],
                "line-color": "#ffffff"
            },
            "interactive": true
        });
    }

    function addMarker(type, lnglat) {
        var marker_red = document.createElement("div")
        marker_red.style.cssText = "width:30px;height:30px";
        marker_red.innerHTML = "<svg t='1594346569381' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='6357' width='32' height='32' xmlns:xlink='http://www.w3.org/1999/xlink'><defs><style type='text/css'></style></defs><path d='M512 0C345.975467 0 152.234667 101.444267 152.234667 359.765333c0 175.3088 276.753067 562.7904 359.765333 664.234667 73.796267-101.444267 359.765333-479.709867 359.765333-664.234667C871.765333 101.512533 678.024533 0 512 0z' p-id='6358' fill='#E8371B'></path></svg><div style='position: absolute;position: absolute;left: 9.3px;top: 3px;font-size: 14px;color: #ffffff;'>终</div>"
        var marker_blue = document.createElement("div")
        marker_blue.style.cssText = "width:30px;height:30px";
        marker_blue.innerHTML = "<svg t='1594346569381' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='6357' width='32' height='32' xmlns:xlink='http://www.w3.org/1999/xlink'><defs><style type='text/css'></style></defs><path d='M512 0C345.975467 0 152.234667 101.444267 152.234667 359.765333c0 175.3088 276.753067 562.7904 359.765333 664.234667 73.796267-101.444267 359.765333-479.709867 359.765333-664.234667C871.765333 101.512533 678.024533 0 512 0z' p-id='6358' fill='#398CF3'></path></svg><div style='position: absolute;position: absolute;left: 9.3px;top: 3px;font-size: 14px;color: #ffffff;'>起</div>"

        if (type == "marker_red") {
            window[type] && window[type].remove();
            var _MarkerArr = lnglat.split(",")
            window[type] = new imapgl.Marker(marker_red).setLngLat([Number(_MarkerArr[0]), Number(_MarkerArr[1])]).addTo(map);
        }
        if (type == "marker_blue") {
            window[type] && window[type].remove();
            var _MarkerArr = lnglat.split(",")
            window[type] = new imapgl.Marker(marker_blue).setLngLat([Number(_MarkerArr[0]), Number(_MarkerArr[1])]).addTo(map);
        }
    }
</script>

</body>
</html>
